 //
//  WBUserAccount.swift
//  simpleWeibo
//
//  Created by 孙林 on 2018/7/8.
//  Copyright © 2018年 孙林. All rights reserved.
//

import UIKit
import YYModel

private let accountFile: NSString = "useraccount.json"

//用户账号信息
class WBUserAccount: NSObject {
    ///访问令牌
    @objc var access_token: String?
    ///用户代号
    @objc var uid: String?
    ///access_token的生命周期，单位是秒数
    ///开发者 5年 试用者 3天
    @objc var expires_in: TimeInterval = 0 {
        didSet {
            expiresData = Date(timeIntervalSinceNow: expires_in)
        }
    }
    ///过期日期
    @objc var expiresData: Date?
    @objc var screen_name: String?
    @objc var avatar_large : String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        //从磁盘加载保存的文件 -> 字典
        //1 加载磁盘文件到二进制数据 如果失败直接返回
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject]
                else {
                return
        }
        
        //2 使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        print("账号模型是: \(self)")
        
//        expiresData = Date(timeIntervalSinceNow: -3600 * 24)
        
        //3 判断token 是否过期
        if expiresData?.compare(Date()) != .orderedDescending {
            print("账号过期")
            
            //清空 token
            access_token = nil
            uid = nil
            
            //删除文件
            try? FileManager.default.removeItem(atPath: path)
        }
        
    }
    
    /**
     1偏好设置  (小)
     2沙盒     归档/plist/json
     3数据库   FMDB/coreData
     4钥匙串   (小) SSKeychain
     */
    func saveAccount() {
        //1模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String : AnyObject]) ?? [:]
        //2移除expires_in字段
        dict.removeValue(forKey: "expires_in")
        
        //3字典 json序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir()
            else {
                return
        }
        
        //4写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
    }
    
}
